<?php

namespace platform\models\authority;


use Yii;
use Exception;
use yii\base\Model;
use yii\base\Module;
use yii\base\Controller;
use yii\caching\TagDependency;
use yii\helpers\VarDumper;


/**
 * Description of Route
 *
 * @author Misbahul D Munir <misbahuldmunir@gmail.com>
 * @since 1.0
 *
 * @property-read mixed $assignedRoutes
 */
class Route extends Model
{

    public $name;
    public $description;

    public function rules()
    {
        return [
            [['name'], 'required'],
            [['description'], 'required'],
            [['description'], 'string', 'max' => 10],
        ];

    }

    const CACHE_TAG = 'route_cache';


    public function update()
    {
        $authManager = \Yii::$app->authManager;
        $permission = $authManager->getPermission($this->name);

        if (!$this->validate()) {
            return $this;
        }

        if (!$permission) {
            $this->addError('name', '权限不存在');
        }

        $permission->description = $this->description;

        $res = $authManager->update($this->name, $permission);

        if (!$res) {
            $this->addError('name', '更新权限失败');
        }

        return $this;
    }

    public function initRoutes()
    {
        $appRoutes = $this->getAppRoutes();
        $assignedRoutes = $this->getAssignedRoutes();
        $authManager = Yii::$app->authManager;

        foreach ($assignedRoutes as $route => $permission) {
            if (!in_array($route, $appRoutes)) {
                $authManager->remove($permission);
            }
        }

        foreach ($appRoutes as $route) {
            if (!in_array($route, array_keys($assignedRoutes))) {
                $permission = $authManager->createPermission($route);
                $authManager->add($permission);
            }
        }
    }

    public function getAssignedRoutes()
    {
        $authManager = Yii::$app->authManager;

        return $authManager->getPermissions();
    }


    /**
     * Get list of application routes
     * @param null $module
     * @return array
     */
    public function getAppRoutes($module = null)
    {
        if ($module === null) {
            $module = Yii::$app;
        } elseif (is_string($module)) {
            $module = Yii::$app->getModule($module);
        }
//        $key = [__METHOD__, Yii::$app->id, $module->getUniqueId()];
//        $cache = Yii::$app->cache;
//        if ($cache === null || ($result = $cache->get($key)) === true) {
//            $result = [];
//            $this->getRouteRecursive($module, $result);
//            if ($cache !== null) {
//                $cache->set($key, $result, 3600, new TagDependency([
//                    'tags' => self::CACHE_TAG,
//                ]));
//            }
//        }

        $result = [];
        $this->getRouteRecursive($module, $result);

        return $result;
    }

    /**
     * Get route(s) recursive
     * @param Module $module
     * @param array $result
     */
    protected function getRouteRecursive($module, &$result)
    {
        $token = "Get Route of '" . get_class($module) . "' with id '" . $module->uniqueId . "'";
        Yii::beginProfile($token, __METHOD__);
        try {
            foreach ($module->getModules() as $id => $child) {
                if (($child = $module->getModule($id)) !== null) {
                    $this->getRouteRecursive($child, $result);
                }
            }

            foreach ($module->controllerMap as $id => $type) {
                $this->getControllerActions($type, $id, $module, $result);
            }

            $namespace = trim($module->controllerNamespace, '\\') . '\\';
            $this->getControllerFiles($module, $namespace, '', $result);
        } catch (\Exception $exc) {
            Yii::error($exc->getMessage(), __METHOD__);
        }
        Yii::endProfile($token, __METHOD__);
    }

    /**
     * Get list controller under module
     * @param Module $module
     * @param string $namespace
     * @param string $prefix
     * @param mixed $result
     * @return mixed
     */
    protected function getControllerFiles($module, $namespace, $prefix, &$result)
    {
        $path = Yii::getAlias('@' . str_replace('\\', '/', $namespace), false);
        $token = "Get controllers from '$path'";
        Yii::beginProfile($token, __METHOD__);
        try {
            if (!is_dir($path)) {
                return;
            }
            foreach (scandir($path) as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                if (is_dir($path . '/' . $file) && preg_match('%^[a-z0-9_/]+$%i', $file . '/')) {
                    $this->getControllerFiles($module, $namespace . $file . '\\', $prefix . $file . '/', $result);
                } elseif (strcmp(substr($file, -14), 'Controller.php') === 0) {
                    $baseName = substr(basename($file), 0, -14);
                    $name = strtolower(preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $baseName));
                    $id = ltrim(str_replace(' ', '-', $name), '-');
                    $className = $namespace . $baseName . 'Controller';
                    if (strpos($className, '-') === false && class_exists($className) && is_subclass_of($className, 'yii\base\Controller')) {
                        $this->getControllerActions($className, $prefix . $id, $module, $result);
                    }
                }
            }
        } catch (\Exception $exc) {
            Yii::error($exc->getMessage(), __METHOD__);
        }
        Yii::endProfile($token, __METHOD__);
    }

    /**
     * Get list action of controller
     * @param mixed $type
     * @param string $id
     * @param Module $module
     * @param string $result
     */
    protected function getControllerActions($type, $id, $module, &$result)
    {
        $token = "Create controller with cofig=" . VarDumper::dumpAsString($type) . " and id='$id'";
        Yii::beginProfile($token, __METHOD__);
        try {
            /* @var $controller Controller */
            $controller = Yii::createObject($type, [$id, $module]);
            $this->getActionRoutes($controller, $result);
        } catch (\Exception $exc) {
            Yii::error($exc->getMessage(), __METHOD__);
        }
        Yii::endProfile($token, __METHOD__);
    }

    /**
     * Get route of action
     * @param Controller $controller
     * @param array $result all controller action.
     */
    protected function getActionRoutes($controller, &$result)
    {
        $token = "Get actions of controller '" . $controller->uniqueId . "'";
        Yii::beginProfile($token, __METHOD__);
        try {
            $prefix = '/' . $controller->uniqueId . '/';
            foreach ($controller->actions() as $id => $value) {

                if ($id == 'options' && isset($value['class']) && $value['class'] == 'yii\rest\OptionsAction') {
                    continue;
                }

                $result[$prefix . $id] = $prefix . $id;
            }
            $class = new \ReflectionClass($controller);
            foreach ($class->getMethods() as $method) {
                $name = $method->getName();
                if ($method->isPublic() && !$method->isStatic() && strpos($name, 'action') === 0 && $name !== 'actions') {
                    $name = strtolower(preg_replace('/(?<![A-Z])[A-Z]/', ' \0', substr($name, 6)));
                    $id = $prefix . ltrim(str_replace(' ', '-', $name), '-');
                    $result[$id] = $id;
                }
            }
        } catch (\Exception $exc) {
            Yii::error($exc->getMessage(), __METHOD__);
        }
        Yii::endProfile($token, __METHOD__);
    }

    /**
     * Ivalidate cache
     */
    public static function invalidate()
    {
        if (Configs::cache() !== null) {
            TagDependency::invalidate(Configs::cache(), self::CACHE_TAG);
        }
    }

    /**
     * Set default rule of parameterize route.
     */
    protected function setDefaultRule()
    {
        if (Configs::authManager()->getRule(RouteRule::RULE_NAME) === null) {
            Configs::authManager()->add(new RouteRule());
        }
    }
}
